<?php
/**
 *与认证有关的方法
 */
class Authhelper{
	public static function auth(){
		/*
		 *这个方法为补全用户认证信息
		 *认证分为三层 session -> [qmx_auth] -> [qmx_s_auth]
		 *后两个存储的认证信息最后都会被存储到session中
		 */
		global $_COOKIE, $_SESSION;
		//验证session中是否有user信息 则直接返回
		if(isset($_SESSION['user']))
			return $_SESSION['user'];
		//验证cookie中是否存在信息
		if(isset($_COOKIE['qmx_auth']) && (!empty($_COOKIE['qmx_auth']))){
			list($uid, $username) = explode("\t", uc_authcode($_COOKIE['qmx_auth'], 'DECODE'));
			list($uid, $username, $email) = uc_get_user($username);
			$_SESSION['user'] = array(
				'uid' => $uid,
				'username' => $username,
				'email' => $email
			);
			//说明登陆信息掉了 同步登陆
			add_action('API_GLOBAL_FOOTER', function(){
				echo uc_user_synlogin(session('user.uid'));
			});
			return $_SESSION['user'];
		}
		if(isset($_COOKIE['qmx_s_auth']) && (!empty($_COOKIE['qmx_s_auth']))){
			//固化的cookie持续很长时间 可能已经失效了 所以要验证密码
			list($uid, $username, $password) = explode("\t", uc_authcode($_COOKIE['qmx_s_auth'], 'DECODE'));
			list($uid, $username, $password, $email) = uc_user_login($username, $password);
			if($uid > 0){
				$_SESSION['user'] = array(
					'uid' => $uid,
					'username' => $username,
					'email' => $email
				);
				//重新同步登陆
				add_action('API_GLOBAL_FOOTER', function(){
					echo uc_user_synlogin(session('user.uid'));
				});
				return $_SESSION['user'];
			}
		}
		return false;
	}
	//登陆
	public static function login($uid, $username){
		if(!headers_sent($file, $linenum)){
			header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');
			cookie('qmx_auth', uc_authcode("$uid\t$username", 'ENCODE'));
		}	
	}
	//固化登陆
	public static function s_login($uid, $username, $password){
		header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');
		cookie('qmx_s_auth', uc_authcode("$uid\t$username\t$password", 'ENCODE'), 31536000);
	}
	//登出
	public static function logout(){
		if(isset($_SESSION['user']))
			unset($_SESSION['user']);
		if(!headers_sent($file, $linenum)){
			header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"');
			cookie('qmx_auth', '', -31536000);
			cookie('qmx_s_auth', '', -31536000);
		}
	}
	//存储验证码
	public static function save_validate($code){
		global $_SESSION;
		$_SESSION['validate'] = array(
			'code' => $code,
			'time' => time(),
		);
	}
	//检查验证码
	public static function check_validate($check){
		if(!isset($_SESSION['validate']))
			return false;
		$check = strtolower($check);
		$code = $_SESSION['validate']['code'];
		$time = (int)$_SESSION['validate']['time'];
		$delay = time() - $time;
		unset($_SESSION['validate']);
		//检查验证码是否有效 有效期10分钟
		if($code == $check && $delay < 600){
			return true;
		}
		return false;
	}
}